package Servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Dao.CourseResourceDao;
import Dao.LearningResourceDao;

/**
 * Servlet implementation class RemoveUploadedFileServlet
 */
//@WebServlet("/RemoveUploadedFileServlet")
public class RemoveUploadedFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RemoveUploadedFileServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");// 解决乱码
		response.setContentType("text/html;charset=utf-8");// 解决乱码
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String CourseID = request.getParameter("CourseID");
		String resourceID = request.getParameter("resourceID");
		String filePath = request.getParameter("filePath");
		String status=request.getParameter("status");
		// FileUtils.delete(entity.getFilePath());
		if(CourseID!=null) {
		if (new CourseResourceDao().deleteCourseResourceById(CourseID) > 0) { // 删除数据库的记录
			/* 删除相应文件 */
			File file = new File(filePath);
			if (file.isFile() && file.exists()) {
				file.delete();
			}
			//out.print("<script type='text/javascript'>alert('删除成功！')</script>");
			if(status.equals("teacher")) {
			response.sendRedirect("JSP_teacherPersonalManage/myExcellentCourses_teacher.jsp");
			}
			else if(status.equals("admin")) {
				response.sendRedirect("JSP_administrator/showAllExcellentCourse.jsp");
			}
		}
		}
		if(resourceID!=null) {
			if (new LearningResourceDao().deleteLearningResourceByResourceId(resourceID) > 0) { // 删除数据库的记录
				/* 删除相应文件 */
				File file = new File(filePath);
				if (file.isFile() && file.exists()) {
					file.delete();
				}
				//out.print("<script type='text/javascript'>alert('删除成功！')</script>");
				if(status.equals("student")) {
				response.sendRedirect("JSP_studentPersonalManage/myRelease_student.jsp");
				}
				else if(status.equals("teacher")) {
					response.sendRedirect("JSP_teacherPersonalManage/myRelease_teacher.jsp");
				}
				else if(status.equals("admin")) {
					response.sendRedirect("JSP_administrator/showAllLearningResource.jsp");
				}
			}
		}
		out.flush();
		out.close();
	}

}
